/* Copyright (C) 2004,2005  The DESIROS Team
    desiros.dev@gmail.com

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
   USA. 
 */


#include "stdarg.h"
#include "crt.h"
#include "libc.h"


/**
 * Max number of environment variables
 */
#define MAX_ENVVARS 1024

char **environ = NULL;


int execv( const char * path,
           char * const argv[] ){

 return  _exec(path ,argv, sizeof(argv));
}

void exit (int status)
{
  _exit(status);
}

int fork()
{
 return _fork();
}

int waitpid(int pid, int *status){
 
     return _waitpid(pid, status);
}


int mount(const char *source, const char *target,
	  const char *filesystemtype, unsigned long mountflags,
	  const char *data)
{
  return _mount(source, target, filesystemtype, mountflags, data);
}


static void * kernel_heap_top = NULL;
int brk(void *end_data_seg)
{
  if (! end_data_seg)
    return -1;

  kernel_heap_top = _brk(end_data_seg);
  return 0;
}

/**
 * The presence of this global variable without any protected access
 * to it explains why the "malloc/calloc" functions below are
 * MT-unsafe !
 */
static void * malloc_heap_top = NULL;
void * malloc (size_t size)
{
  void * retval;

  if (size <= 0)
    return NULL;

  /* Align on a 4B boundary */
  size = ((size-1) & ~3) + 4;

  if (! kernel_heap_top)
    kernel_heap_top = _brk(0);

  if (! malloc_heap_top)
    malloc_heap_top = kernel_heap_top;

  retval = malloc_heap_top;
  malloc_heap_top += size;

  _brk(malloc_heap_top);
  return retval;
}


void free(void *ptr)
{
  //  Free ignored (not implemented yet)
}

int open(const char *path, int oflag ){

   return _open( path, oflag);
}

int read(int fd, char * buf, size_t len)
{
   
  return _read(fd, buf, len);
}


int write(int fd, const char * buf, size_t len)
{

    return _write(fd, buf, len);

}

int close(int fd)
{
  return _close(fd);
}


int printf (const char *format, ...)
{
  char buff[4096];
  va_list ap;

  va_start(ap, format);
  vsnprintf(buff, sizeof(buff), format, ap);
  va_end(ap);

  return write (1, buff, strlen(buff));
}



